<template>
  <ContentWrap>
    <div :style="`height:${contentHeight}px`">
    <div class="routeHeader mb-5px">
      <el-button class="mr-5px" type="primary" @click="submitForm" :disabled="formLoading"
        >保 存</el-button>
      <el-button @click="goBack">关 闭</el-button>
    </div>
  <div>
  <div class="subTitle">基本信息</div>
  <el-form
     ref="formRefs"
     :model="formData"
     :rules="formRules"
     :inline="true"
     label-width="110px"
     v-loading="formLoading"
    >
   <template v-if="status">
   <el-form-item label="点检模板编号" prop="spotTemplateNumber" >
     <el-input v-model="formData.spotTemplateNumber" disabled  />
   </el-form-item>
   </template>
   <el-form-item label="点检模板名称" prop="spotCheckTemplateName">
     <el-input v-model="formData.spotCheckTemplateName" placeholder="请输入点检模板名称" />
   </el-form-item>
   <el-form-item label="设备类型" prop="dictDeviceType">
     <el-select
    v-model="formData.dictDeviceType"
    placeholder="请选择设备类型"
    clearable
    class="!w-220px"
    @change="((val)=>{selectChange(val,1)})"
  >
  <el-option
      v-for="dict in getIntDictOptions('dict_device_type')"
      :key="dict.value"
      :label="dict.label"
      :value="dict.value"
    />
  </el-select>
</el-form-item>
<el-form-item label="设备名称" prop="deviceName">
  <!-- <el-input 
  v-model="formData.deviceName" 
  placeholder="请输入设备名称" 
  clearable
  @input="((val)=>{selectChange(val,2)})"
  /> -->
  <el-select
    v-model="formData.deviceName"
    placeholder="请选择设备名称"
    filterable
    clearable
    remote
    reserve-keyword
    class="!w-220px"
    @change="((val)=>{selectChange(val,2)})"
  >
    <el-option
      v-for="item in deviceNameList"
      :key="item.id"
      :label="item.deviceName"
      :value="item.deviceName"
    />
  </el-select>
  </el-form-item>
  <el-form-item label="设备编码" prop="deviceCode">
  <el-select
    v-model="formData.deviceCode"
    placeholder="请选择设备编码"
    filterable
    clearable
    remote
    reserve-keyword
    class="!w-220px"
    @change="((val)=>{selectChange(val,3)})"
  >
    <el-option
      v-for="item in deviceCodeList"
      :key="item.id"
      :label="item.deviceCode"
      :value="item.deviceCode"
    />
  </el-select>
  </el-form-item>
  <el-form-item label="状态" prop="dictEnableStatus">
    <el-select
    v-model="formData.dictEnableStatus"
    placeholder="请选择状态"
    clearable
    class="!w-220px"
  > 
        <el-option
      v-for="dict in getIntDictOptions('dict_enable_status')"
      :key="dict.value"
      :label="dict.label"
      :value="dict.value"
    />
      </el-select>
    </el-form-item>
</el-form>
    </div>
    <div class="subTitle">点检项目配置</div>
    <el-button class="createBtn" type="primary" @click="openForm('create')" >新增</el-button>
   <el-table
    ref="multipleTableRef" 
    :data="list"
    border 
    class="table-box"
    :min-height="contentHeight"
    >
      <el-table-column label="序号" align="left" header-align="left" type="index" />
      <el-table-column label="点检项目编号" align="left" header-align="left" prop="spotCheckProjectCode" />
      <el-table-column label="点检项目名称" align="left" header-align="left" prop="spotCheckProjectName" />
      <el-table-column label="判断基准" align="left" header-align="left" prop="criterion" />
      <el-table-column label="部位" align="left" header-align="left" prop="part" />
      <el-table-column label="实施时间" align="left" header-align="left" prop="implementationTime" />
      <el-table-column label="点检方式" align="left" header-align="left" prop="spotCheckMethod" />
      <el-table-column label="实施周期" align="left" header-align="left" prop="dictImplementationCycle" >
      <template #default="scope">
        <byte-tag
          className="test"
          :type="DICT_TYPE.DICT_IMPLEMENTATION_CYCLE"
          :value="scope.row.dictImplementationCycle"
        />
      </template>
      </el-table-column>
      <el-table-column label="填写类型" align="left" header-align="left" prop="dictFillingType">
      <template #default="scope">
        <byte-tag
          className="test"
          :type="DICT_TYPE.DICT_FILLING_TYPE"
          :value="scope.row.dictFillingType"
        />
      </template>
      </el-table-column>
      <el-table-column label="操作" align="left" header-align="left">
        <template #default="scope">
          <el-button
            link
            type="danger"
            @click="delRow(scope.$index)"
            v-hasPermi="['config:org-team-archives:update']"
          >
            移除行
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</ContentWrap>
   <el-dialog
    v-model="DialogVisible"
    title="提示"
    width="30%"
    align-center
  >
    <span>设备编码已存在点检模板，是否覆盖</span>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="Overwrite(false)">否</el-button>
        <el-button type="primary" @click="Overwrite(true)">
          是
        </el-button>
      </span>
    </template>
  </el-dialog>
   <!-- 表单弹窗：添加/修改 -->
<DeviceCheckTemplateDialog ref="formRef"  @select-data="selectData" :selectForm="list"/>
</template>

<script setup>
import {getIntDictOptions,DICT_TYPE } from '@/utils/dict'
import * as DeviceCheckTemplateApi from '@/api/config/deviceCheckTemplate'
import { useTagsViewStore } from '@/store/modules/tagsView'
import DeviceCheckTemplateDialog from './DeviceCheckTemplateDialog.vue'
import ByteTag from './ByteTag.vue'
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const DialogVisible = ref(false)// 覆盖确认弹窗
const status = ref()//编辑或更新状态
const formData = ref({
  id: undefined,
  spotTemplateNumber: undefined,
  spotCheckTemplateName: undefined,
  deviceName: undefined,
  dictDeviceType: undefined,
  deviceCode: undefined,
  dictEnableStatus: undefined
})
const multipleTableRef = ref()
const formRef=ref() //点检配置
const formRefs =ref() //基本信息
const formRules = reactive({
  spotTemplateNumber: [{ required: false, message: ' ', trigger: 'blur' }],
  spotCheckTemplateName: [{ required: true, message: '点检模板名称不能为空', trigger: 'blur'}],
  dictDeviceType: [{ required: true, message: '设备类型不能为空', trigger: 'change' }],
  dictEnableStatus: [{ required: true, message: '状态不能为空', trigger: 'blur' }]
})


// 选择
const deviceNameList =ref([])
const deviceCodeList =ref([])
const selectDeviceType = ref()//设备类型选中的值
const selectChange = async(val,index)=>{  //存放设备类型的值
  //  选中设备类型时
  if(index === 1){
    console.log(val,'val')
      if(!val){
        deviceCodeList.value=[]
        deviceNameList.value=[]
        formData.value.deviceName = ''
        formData.value.deviceCode=''
        selectDeviceType.value=''
      }else{
        deviceCodeList.value=[]
        deviceNameList.value=[]
        formData.value.deviceName = ''
        formData.value.deviceCode=''
        selectDeviceType.value = val
      let data = await DeviceCheckTemplateApi.getDeviceMessageList({
        deviceType:val
      })
    data.forEach(item=>{
      deviceNameList.value.push({
        deviceName:item.deviceName,
      })
    })
      }
    // 选中设备名称时
  }else if(index === 2){
    if(!val){
        deviceCodeList.value=[]
        formData.value.deviceCode=''
        // 没有选中设备类型时
      }else if(!selectDeviceType.value){
        return
        // 同时存在设备类型、设备名称时
      }else{
        deviceCodeList.value=[]
        formData.value.deviceCode=''
        let data = await DeviceCheckTemplateApi.getDeviceMessageList({
        deviceType:selectDeviceType.value,
        deviceName:val
    })
        data.forEach(item=>{
          if(item.deviceName === val)
            deviceCodeList.value=[{
            deviceCode:item.deviceCode
           }]
    })
      }

  }
}

//删除行
const delRow =(index)=>{
  list.value.splice(index,1)
}

//用来渲染项目配置
let list =ref()
// 获取子组件传递的项目配置
const selectData=(msg)=>{
  console.log(list.value,'list.value')
  if(!list.value){
    list.value = msg
  }else{
    list.value = [...list.value,...msg]
  }
}


/** 添加/修改操作 */
const openForm = (type) => {
  // localStorage.removeItem('projectList')
  // if(list.value) localStorage.setItem('projectList',JSON.stringify(list.value))
  formRef.value.open(type)
}

const { query } = useRoute() // 路由的查询
// /** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRefs) return
  const valid = await formRefs.value.validate()
  if (!valid) return
  console.log('list.value',list.value)
  if(!list.value||list.value.length==0){
    message.info('请添加点检项目配置')
    return
  }
  let dataList=ref([]) //提交数据
  let temp = [] // 保存点检配置项的ID
    list.value.forEach((item)=>{
    temp.push(item.id.toString())
    dataList.value={
    id:undefined,
    spotTemplateNumber: '',
    spotCheckTemplateName: formData.value.spotCheckTemplateName,
    deviceName: formData.value.deviceName,
    dictDeviceType: formData.value.dictDeviceType,
    deviceCode:  formData.value.deviceCode,
    dictEnableStatus:  formData.value.dictEnableStatus,
    configDeviceCheckUpkeepId:temp
  }
})
  // 提交请求
  formLoading.value = true
  const data = dataList.value
  try {
    if (query.type == 'create') {
      //只存在设备类型，设备名称
      if(!formData.value.deviceCode){
       //判断是否选设备类型
        if(!formData.value.deviceName){
           const mes =  await DeviceCheckTemplateApi.validateDeviceCheckTemplate(
        {
          deviceType:formData.value.dictDeviceType,
        })
        //没有返回信息即通过校验无需覆盖
        if(!mes){
          await DeviceCheckTemplateApi.createDeviceCheckTemplate(data)
          list.value=''
          goBack()
        }else{
          DialogVisible.value=true
        }  
        }else{
        const mes = await DeviceCheckTemplateApi.validateDeviceCheckTemplate(
        {
          deviceType:formData.value.dictDeviceType,
          deviceName:formData.value.deviceName
        })
        if(!mes){
          await DeviceCheckTemplateApi.createDeviceCheckTemplate(data)
          list.value=''
          goBack()
        }else{
          DialogVisible.value=true
        }
        }   
      }else{
      // await DeviceCheckTemplateApi.createDeviceCheckTemplate(data)
      //
      const mes = await DeviceCheckTemplateApi.validateDeviceCheckTemplate(
        {
          deviceType:formData.value.dictDeviceType,
          deviceName:formData.value.deviceName
        })
        if(!mes){
          await DeviceCheckTemplateApi.createDeviceCheckTemplate({
          deviceType:formData.value.dictDeviceType,
          deviceName:formData.value.deviceName
          })
          list.value=''
          goBack()
        }else{
          DialogVisible.value=true
        }
      // list.value=''
      message.success(t('common.createSuccess'))
      // goBack()
      }
    } else {
      data.id=query.id
      data.spotTemplateNumber = formData.value.spotTemplateNumber
      await DeviceCheckTemplateApi.updateDeviceCheckTemplate(data)
      message.success(t('common.updateSuccess'))
      goBack()
    }
    dialogVisible.value = false
    // 发送操作成功的事件
  } 
  finally {
    formLoading.value = false
  }
}

// //是否覆盖
const Overwrite=async (bol,data)=>{
  let dataList=ref([])
  let temp = []
  list.value.forEach((item)=>{
  temp.push(item.id.toString())
  dataList.value={
  id:undefined,
  spotTemplateNumber: '',
  spotCheckTemplateName: formData.value.spotCheckTemplateName,
  deviceName: formData.value.deviceName,
  dictDeviceType: formData.value.dictDeviceType,
  deviceCode:  formData.value.deviceCode,
  dictEnableStatus:  formData.value.dictEnableStatus,
  configDeviceCheckUpkeepId:temp,
  isCover:bol
} 
  })
  data = dataList.value
  await DeviceCheckTemplateApi.createDeviceCheckTemplate(data)
  DialogVisible.value=false
  list.value=''
  goBack()
}



/**返回 */
const tagsViewStore = useTagsViewStore()
const route = useRouter() // 路由
const goBack = async() => {
  //获取当前路由并删除tagView
  tagsViewStore.delView(route.currentRoute.value)
  console.log('route.currentRoute',route.currentRoute )
  //跳转列表页
  route.push({
    path:'/config/config/device/device-check-template'
  })
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    spotTemplateNumber: undefined,
    spotCheckTemplateName: undefined,
    deviceName: undefined,
    dictDeviceType: undefined,
    deviceCode: undefined,
    dictEnableStatus: undefined
  }
  // formRef.value?.resetFields()
}

/** 初始化 */
const contentHeight = ref(0)
onMounted(async () => {
  console.log(multipleTableRef.value.$el.clientHeight,'123123')
  query.type==='create'?status.value=false:status.value=true
  // const queryParamsHeight = queryFormRef.value.$el.clientHeight + 2
  contentHeight.value = document.body.clientHeight - 152
  await resetForm()
  if (query.id) {
    formData.value = await DeviceCheckTemplateApi.getDeviceCheckTemplate(query.id) 
    list.value=formData.value.configDeviceCheckUpkeepList
  }
  formLoading.value = false
})
</script>
<style scoped>
.subTitle {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 20px;
}
.createBtn{
  margin-bottom: 10px;
}

/* .table-box{
    height:calc(100vh - 190px);
} */
</style>